package com.chenailin.www.service;

import com.chenailin.www.dao.PublicDAO;
import com.chenailin.www.daoimpl.PublicDAOImpl;
import com.chenailin.www.exception.ServiceException;
import com.chenailin.www.pojo.Administrator;
import com.chenailin.www.pojo.Student;
import com.chenailin.www.pojo.User;

import java.sql.SQLException;

public class PublicService {
    // 面向接口编程
    private final PublicDAO publicDAO = new PublicDAOImpl();

    // 登录逻辑
    public User login(int id, int userType) {
        try {
            // 数据库里没账号信息，需要先注册
            if (!publicDAO.hasAccounts()) {
                System.out.println("系统中无账户，请先注册");
                return null;
            }
            // 验证数据库中是否有此账号
            User user = publicDAO.selectUser(id, userType);
            if(user==null) {
                System.out.println("账号不存在");
                return null;
            }
            return user;
        } catch (SQLException e) {
            throw new ServiceException("登录失败", e);
        }
    }

    // 注册逻辑
    public boolean register(User user, int userType){
        try {
            // 数据验证
            validateUser(user ,userType);
            // 验证数据库中是否有此账号
            if (publicDAO.selectUser(user.getId(), userType) != null) {
                return false;
            }
            return addUser(user, userType);

        } catch (SQLException e) {
            throw new ServiceException("注册失败", e);
        }
    }

    // 判断密码是否一致
    public boolean arePasswordsEqual(String correctPassword, String inputPassword) {
        return inputPassword.equals(correctPassword);
    }

    // 添加用户数据
    public boolean addUser(User user, int userType) {
        // 1. 数据验证
        validateUser(user ,userType);
        // 2. 数据库操作
        try {
            // 验证是否成功
            if (userType == 1) {
                return publicDAO.addAdmin((Administrator) user);
            }else {
                return publicDAO.addStudent((Student) user);
            }
        } catch (SQLException e) {
            throw new ServiceException("添加用户数据失败", e);
        }
    }

    // 是否为有效账号
    private void validateUser(User user, int userType) throws IllegalArgumentException {
        // 姓名非空检查
        if(userType==2) {
            Student stu=(Student) user;
            if (stu.getStuName() == null || stu.getStuName().trim().isEmpty()) {
                throw new IllegalArgumentException("名字不能为空！");
            }
        }
    }

    // 添加用户数据
    public boolean hasAccounts() {
        try {
            return publicDAO.hasAccounts();
        } catch (SQLException e) {
            throw new ServiceException("无账号数据", e);
        }
    }
}
